<?php
/***************************************************************
*  Copyright notice
*  (c) 2009, jianyuzhu@gmail.com
*  All rights reserved
*  This script is part of the PPEMI project.
***************************************************************/

class CoreCryptURI {
	
	//constructor
	function CoreCryptURI() {
		
		$this->codemap = array(
				'0' => 'a', '1' => 'b', '2' => 'c', '3' => 'd', '4' => 'e', '5' => 'f', '6' => 'g',
				'7' => 'h', '8' => 'i', '9' => 'j', '10' => 'k', '11' => 'l', '12' => 'm', '13' => 'n',
				'14' => 'o', '15' => 'p', '16' => 'q', '17' => 'r', '18' => 's', '19' => 't',
				'20' => 'u', '21' => 'v', '22' => 'w', '23' => 'x', '24' => 'y', '25' => 'z',
				'26' => '2', '27' => '3', '28' => '4', '29' => '5', '30' => '6', '31' => '7',
					);
		$this->decodemap = array(
				'a' => '0', 'b' => '1', 'c' => '2', 'd' => '3', 'e' => '4', 'f' => '5', 'g' => '6',
				'h' => '7', 'i' => '8', 'j' => '9', 'k' => '10', 'l' => '11', 'm' => '12', 'n' => '13',
				'o' => '14', 'p' => '15', 'q' => '16', 'r' => '17', 's' => '18', 't' => '19',
				'u' => '20', 'v' => '21', 'w' => '22', 'x' => '23', 'y' => '24', 'z' => '25',
				'2' => '26', '3' => '27', '4' => '28', '5' => '29', '6' => '30', '7' => '31',
					);
	}
	
	//methods
	function encode($value) {
		if( strlen($value) == 0 ) return '';
		//string to byte
		$bs = '';
		$a = implode('', unpack("H*", $value));
		for($i=0, $n=strlen($a); $i<$n; $i+=2) {
			$b = substr($a, $i, 2);
			//hex to bin
			$b = base_convert($b, 16, 2);
			//align
			$bs .= str_pad($b, 8, '0', STR_PAD_LEFT);
		}
		
		$bl = strlen($bs);
		$pc = intval($bl / 5);
		$pl = $bl % 5;
		if( $pl > 0 ) {
			$pc++;
		}
		$cc = $pc * 5;
		
		$v = '';
		for($i=0; $i<$cc; $i+=5) {
			$l = 5;
			$f = false;
			if( $i + 5 > $bl ) {
				$l = $pl;
				$f = true;
			}
			$b = substr($bs, $i, $l);
			if( $f == true ) {
				$b = str_pad($b, 5, '0');
			}
			$b = bindec($b);
			$v .= $this->codemap[$b];
		}		
		
		return $v;
	}
	
	//
	function decode($value) {
		if( strlen($value) == 0 ) return '';
		$bs = '';
		for($i=0, $n=strlen($value); $i<$n; $i++) {
			$b = $this->decodemap[$value{$i}];
			$b = decbin($b);
			$b = str_pad($b, 8, '0', STR_PAD_LEFT);
			$bs .= substr($b, 3, 5);
		}
		
		$bl = strlen($bs);
		$pc = intval($bl / 8);
		
		$as = '';
		for($i=0, $j=0; $i<$pc; $i++) {
			$s = substr($bs, $j, 8);
			$as .= chr(bindec($s));
			
			$j += 8;
			
		}
		
		return $as;
	}
}
//
?>